package com.pl.itsense.gwt.clientzone.server;



import java.security.MessageDigest;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.persistence.EntityManager;

import com.pl.itsense.gwt.clientzone.client.ClientZoneService;
import com.pl.itsense.gwt.clientzone.model.EventType;
import com.pl.itsense.gwt.clientzone.model.ITSenseEvent;
import com.pl.itsense.gwt.clientzone.model.Member;
import com.pl.itsense.gwt.clientzone.model.MemberDTO;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */




@SuppressWarnings("serial")
public class ClientZoneServiceImpl extends RemoteServiceServlet implements ClientZoneService {
	private static final Logger log = Logger.getLogger(ClientZoneServiceImpl.class.getName());

	EntityManager em = EMF.get().createEntityManager();
	
	  private String getHashCode(String text){
		  StringBuffer result = new StringBuffer();

		  try {
			  MessageDigest md = MessageDigest.getInstance("MD5");
			  md.reset();
		      md.update(text.getBytes());
		      MessageDigest tc1 = (MessageDigest) md. clone();
		      byte[] code = tc1.digest();
		      for (int i = 0 ; i < code.length; i++){
		    	  result.append(Integer.toHexString(0xFF & code[i]));  
		      }
   
		  }catch (Exception ex) {
			  ex.printStackTrace();
		  }
	      return result.toString();
	  }

	  
	  Member findMember(String login){
		  Member member = null;
		  try{
			  member = (Member)em.createQuery("SELECT FROM Member m WHERE m.login = :login").setParameter("login", login).getSingleResult();
			  
		  }catch(Exception ex){
			  member = null;
		  }
		  return member; 
	  }
	
	  @Override
	  public MemberDTO login(String login, String password) throws IllegalArgumentException {
		  Member member = findMember(login);
		  
		  MemberDTO memberDTO = null;
		  if (member != null){
			  memberDTO = new MemberDTO(member);
			  if (member.getActive() == false) memberDTO.setId(new Long(-1));
		  }
		  event(new Long(-1), EventType.LOGIN,login);	
		  return memberDTO;
	  }

	  @Override
	  public MemberDTO register(MemberDTO memberDTO) throws IllegalArgumentException {

		  Member member = findMember(memberDTO.getLogin());
		  if (member == null){
			  memberDTO.setPassword(getHashCode(memberDTO.getPassword()));
			  member = new Member(memberDTO);
			  member.setActive(false);
			  member.setRegistrationHash(getHashCode(member.toString()) );
			  em.persist(member);
			  member = em.merge(member);
			  memberDTO.setId(member.getId());
			  sendRegistrationMail(member);
			  log.info("register id = " + member.getId() + " hash=" + member.getRegistrationHash());
		  }else{
			  memberDTO.setId(new Long(-1));
			  
		  }
		  event(memberDTO.getId(), EventType.REGISTER,"");	
		  memberDTO.setRole(0);
		  return memberDTO;
	  }
	  
	  
	@Override
	public MemberDTO update(MemberDTO memberDTO) throws IllegalArgumentException {
		  event(memberDTO.getId(), EventType.UPDATE_PROFILE,"");	
		  Member member = em.find(Member.class, memberDTO.getId());
		  if (member != null){
			  member.setCompany(memberDTO.getCompany());
			  member.setComment(memberDTO.getComment());
			  member.setEmail(memberDTO.getEmail());
			  member.setFirstName(memberDTO.getFirstName());
			  member.setLastName(memberDTO.getLastName());
			  member.setIntrests(memberDTO.getIntrests());
			  member.setNewsletter(memberDTO.getNewsletter());
			  member.setPhone(memberDTO.getPhone());
			  em.persist(member);
		  }
		  return memberDTO;
	}
	
	@Override
	public Boolean event(Long memberId, int eventType, String msg) throws IllegalArgumentException {
		ITSenseEvent event = new ITSenseEvent();
		event.setMemberId(memberId);
		event.setEventId(eventType);
		event.setMessage(msg);
		Date today = new Date();
		event.setTimeStamp(new Long(today.getTime()));
		em.persist(event);
		em.merge(event);
		return true;
	}
	
	@Override
	public Boolean removeAccount(Long memberId) throws IllegalArgumentException {
		event(memberId, EventType.REMOVE_ACCOUNT, "");
		em.createQuery("DELETE FROM Member m WHERE m.id = :id").setParameter("id", memberId).executeUpdate();
		return true;
	}
	
	private boolean sendRegistrationMail(Member member){
		
		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);

		String msgBody = "Witaj "+member.getLogin()+" \n";
		msgBody += "Ten adres posłużył do założenia konta w serwisie ITSense Strefa Klienta (www.strefaklienta.itsense.com.pl).\n";
		msgBody += "W celu dokonania aktywacji konta kliknij na poniższy link\n";
		msgBody += "http://itsenseclientzone.appspot.com/clientzone/registration?id="+member.getId()+"&hash="+member.getRegistrationHash()+"\n";
		msgBody += "Zapraszamy do współpracy i korzystania z serwisu.\n";
		msgBody += "Honorata Bojar \n";
		msgBody += "ITSense - Open Source Business Intelligence Systems \n";
		msgBody += "www.itsense.com.pl \n";

		try {
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress("p.pretki@gmail.com","ITSense - Open Source BI"));
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(member.getEmail()));
			msg.setSubject("Potwierdzenie rejestracji - ITSense Strefa Klienta");
			msg.setText(msgBody);
			Transport.send(msg);
			System.out.println("Wyslana wiadomosc");
		} catch (Exception e) {
			System.out.println(e);
		}return true;
	}
	
	
}
